#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
拼多多数据抓取工具安装脚本
"""

import os
import sys
import subprocess
import platform

def check_python_version():
    """检查Python版本"""
    version = sys.version_info
    if version.major < 3 or (version.major == 3 and version.minor < 7):
        print("❌ 需要Python 3.7或更高版本")
        print(f"当前版本: {version.major}.{version.minor}.{version.micro}")
        return False
    print(f"✅ Python版本检查通过: {version.major}.{version.minor}.{version.micro}")
    return True

def install_dependencies():
    """安装依赖包"""
    print("\n📦 安装依赖包...")
    
    try:
        # 升级pip
        print("升级pip...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
        
        # 安装依赖
        print("安装项目依赖...")
        subprocess.check_call([sys.executable, "-m", "pip", "install", "-r", "requirements.txt"])
        
        print("✅ 依赖安装完成")
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 依赖安装失败: {e}")
        return False

def install_chrome_driver():
    """安装ChromeDriver"""
    print("\n🌐 检查Chrome浏览器...")
    
    system = platform.system().lower()
    
    if system == "windows":
        # Windows系统
        chrome_paths = [
            r"C:\Program Files\Google\Chrome\Application\chrome.exe",
            r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
        ]
    elif system == "darwin":
        # macOS系统
        chrome_paths = [
            "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
        ]
    else:
        # Linux系统
        chrome_paths = [
            "/usr/bin/google-chrome",
            "/usr/bin/chromium-browser"
        ]
    
    chrome_found = False
    for path in chrome_paths:
        if os.path.exists(path):
            print(f"✅ 找到Chrome浏览器: {path}")
            chrome_found = True
            break
    
    if not chrome_found:
        print("⚠️  未找到Chrome浏览器")
        print("请手动安装Chrome浏览器:")
        print("  Windows: https://www.google.com/chrome/")
        print("  macOS: https://www.google.com/chrome/")
        print("  Linux: sudo apt-get install google-chrome-stable")
        return False
    
    print("✅ Chrome浏览器检查完成")
    return True

def create_directories():
    """创建必要的目录"""
    print("\n📁 创建目录...")
    
    directories = ["output"]
    
    for directory in directories:
        if not os.path.exists(directory):
            os.makedirs(directory)
            print(f"✅ 创建目录: {directory}")
        else:
            print(f"✅ 目录已存在: {directory}")

def test_installation():
    """测试安装"""
    print("\n🧪 测试安装...")
    
    try:
        # 测试导入
        import requests
        import beautifulsoup4
        import selenium
        import fake_useragent
        import cloudscraper
        
        print("✅ 基础依赖导入成功")
        
        # 测试ChromeDriver
        try:
            import undetected_chromedriver
            print("✅ undetected-chromedriver导入成功")
        except ImportError:
            print("⚠️  undetected-chromedriver导入失败，可能需要手动安装")
        
        # 测试Playwright
        try:
            import playwright
            print("✅ playwright导入成功")
        except ImportError:
            print("⚠️  playwright导入失败，可能需要手动安装")
        
        return True
        
    except ImportError as e:
        print(f"❌ 依赖导入失败: {e}")
        return False

def main():
    """主安装函数"""
    print("=" * 60)
    print("拼多多数据抓取工具安装程序")
    print("=" * 60)
    
    # 检查Python版本
    if not check_python_version():
        return False
    
    # 安装依赖
    if not install_dependencies():
        return False
    
    # 检查Chrome浏览器
    install_chrome_driver()
    
    # 创建目录
    create_directories()
    
    # 测试安装
    if not test_installation():
        return False
    
    print("\n" + "=" * 60)
    print("🎉 安装完成！")
    print("=" * 60)
    print("\n使用方法:")
    print("1. 运行测试: python test_scraper.py")
    print("2. 交互式运行: python run.py")
    print("3. 直接运行: python pdd_scraper.py")
    print("4. 批量抓取: python batch_scraper.py")
    print("\n注意事项:")
    print("- 首次使用可能需要下载ChromeDriver")
    print("- 建议使用代理IP避免被封")
    print("- 请遵守网站使用条款")
    
    return True

if __name__ == "__main__":
    try:
        success = main()
        sys.exit(0 if success else 1)
    except KeyboardInterrupt:
        print("\n\n👋 安装已取消")
        sys.exit(1)
    except Exception as e:
        print(f"\n❌ 安装过程中发生错误: {e}")
        sys.exit(1) 